$(function(){
	
	$('.icon-del').on('click',delImg);
	//随手拍添加图片
	
	function delImg(){
		$(this).parent().animate({width:0,height:0},400,function(){
			$(this).remove();
		});
	}
	
	var num = 0;
	var limit_num = 9;
	var images = {
			localId: [],
			serverId: []
	};
	$('.poblish-img-add').click(function(event) {
		wx.chooseImage({
			count: 9,
			success: function(res)
			{
				images.localId = res.localIds;
		        if (images.localId.length == 0) {
		  	      	showToast('请先选择图片');
					return;
		  	    }
		        var i = 0; 
		        var length = images.localId.length;
		        images.serverId = [];
		        
		        function upload() 
		        {
					if(num>=limit_num-1)
					{
						$('.poblish-img-add').hide();
					}
					var img;
		        	wx.uploadImage({
		        		localId: images.localId[i],
		      		    success: function (res) {
		      		    	i++;
		      		    	num++;
		      		    	images.serverId.push(res.serverId);
		      		    	img = res.serverId;
		      		    	add_img_div(images.localId[i-1],img);
		      		    	if(num>=limit_num)
							{
								return;
							}
		      		    	if(i<length)
		      		    	{
		      		    		upload();
		      		    	}
		      		    }
		        	});
		        }
		        upload();
			}
		});
	});
	
	function add_img_div(limg, simg)
	{
		var $parent = $('.poblish-img-add');
		var index=$parent.index();
		var src = 'images/poblish.png';
		var str='<li><div class="added-img" style="background-image:url('+limg+')"><img src="'+ img_url +'/o2.png" class="oimg"></div><span class="del-img icon-del"></span><input type="hidden" name="all_pic[]" value="'+ simg +'"></li>';
		$parent.before(str);
		$parent.parent().find('li').eq(index).find('.icon-del').on('click',delImg);
	}
	
	$('.poblish-submit').click(function(e){
		e.preventDefault();
		var _this = $(this);
		var type = _this.attr('data-type');
		if(type == 'yes')
		{
			var url = $('.tryForm').attr('data-url');
			if(url == undefined || url == '')
			{
				showToast('配置错误');
				return false;
			}
			var data = getPostData('tryForm');
			_this.attr('data-type', 'no');
			$.ajax({
				url: url,
				type: 'POST',
				dataType: 'json',
				data: data,
				success: function(res){
					showToast(res.info);
					if(res.status == 1)
					{
						setTimeout(function(){
							location.href = res.url;
						}, 2000);
					}
					_this.attr('data-type', 'yes');
				},
				error: function(res){
					showToast('系统繁忙');
					_this.attr('data-type', 'yes');
				}
			});
		}
		else
		{
			showToast('数据提交中');
		}
	});
	
});